package cn.yangliu.shiro;

import cn.yangliu.comm.BaseComponent;
import cn.yangliu.comm.CommConst;
import cn.yangliu.comm.entity.JsonResult;
import cn.yangliu.comm.tools.WebUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者 杨柳
 * 创建时间 2017-08-29 20:25
 */
@ControllerAdvice
public class AuthExceptionAdvice extends BaseComponent {

    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request, HttpServletResponse response) {
        if (WebUtils.checkJsonAjax()) {
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode(CommConst.LOGIN_ERROR_CODE);
            jsonResult.setMsg(ShiroConst.AUTH_ERROR_MSG);
            WebUtils.printData(jsonResult, response);
            return null;
        }

        //其他返回值的方法
        //有配置授权异常的页面
        if (!StringUtils.isEmpty(ShiroConst.AUTH_ERROR_VIEW)) {
            WebUtils.setAttribute4Request(ShiroConst.AUTH_ERROR_KEY, ShiroConst.AUTH_ERROR_MSG);
            return new ModelAndView(ShiroConst.AUTH_ERROR_VIEW);
        }
        throw e;
    }


}
